package com.bshinfo.web.base.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

public class FileUtil 
{
	
	public static void downloadFile(final File file, String fileName,
			HttpServletResponse response) throws IOException 
	{
		InputStream inputStream = null;
		OutputStream outputStream = null;
		try
		{
			// 设置response
			response.reset();
			response.setCharacterEncoding("UTF-8"); 
			response.setContentType("multipart/form-data;charset="+ "UTF-8");
			response.setHeader( "Content-Disposition", "attachment;filename=" + new String( fileName.getBytes(System.setProperty("sun.jnu.encoding","utf-8")), "ISO8859-1" ) );

			// 生成文件输入字节流
			inputStream = new FileInputStream(file);
			// 生成文件输出字节流
			outputStream = response.getOutputStream();
			// 字节数组
			byte[] tmp = new byte[1024];
			// 读取字节长度
			int length = 0;
			while ((length = inputStream.read(tmp)) > 0) 
			{
				outputStream.write(tmp, 0, length);
			}
			outputStream.flush();
		}catch(Exception e)
		{
			e.printStackTrace();
		}finally
		{
			if(outputStream != null)
			{
				outputStream.close();
			}
			if(inputStream != null)
			{
				inputStream.close();
			}
		}
	}
}
